package com.cr.mrapp.Controller;


import com.cr.mrapp.entity.Item;
import com.cr.mrapp.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/item")
public class ItemController {

    //依赖业务逻辑层代码
    @Autowired
    private ItemService itemService;

    //控制方法为了获取页面
    @RequestMapping("/addItem.html")
    public String toAddItem(){
        return "addItem";
    }

    @RequestMapping("/itemList.html")
    public  String toItemList(){
        return "itemList";
    }


    //控制方法为了接收数据
    @RequestMapping("/add.do")
    @ResponseBody
    public Object addItem(@RequestBody Item body){

        int row = itemService.addItem(body);
        if(row>0){
            return "ok";
        }else {
            return "fail";
        }
    }

    @RequestMapping("/delete.do")
    @ResponseBody
    public Object deleteById(int id){
        Map<String,Object> responseData = new HashMap<>();
        int row = itemService.deleteById(id);
        if(row>0){
            responseData.put("code", 200);
            responseData.put("msg","删除成功");
            responseData.put("data",row);
        }else {
            responseData.put("code", 500);
            responseData.put("msg","删除失败");
            responseData.put("data",0);
        }
        return responseData;
    }

    @RequestMapping("/itemList.do")
    @ResponseBody
    public Object findByPage(int page, int limit){

        List<Object> list = itemService.findByPage(page, limit, null);
        int count = itemService.findCount();

        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","查询成功");
        map.put("count",count);
        map.put("data",list);
        return map;
    }
}
